<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use QL\QueryList;
use App\Models\Movie;
use Illuminate\Support\Str;
class GetMoviePlayerSource extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'daka:get-movie-player-source
                            {--id=0 : 采集指定 ID 的电影详情（id 来自豆瓣）}';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '获取电影可以在哪里看';

    protected $ql;
    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
        $this->ql = QueryList::rules([
            'name' => ['a.playBtn', 'data-cn'], // 在哪里看
            'player_url' => ['a.playBtn', 'href'], // 唯一地址
            'content' => ['span.buylink-price', 'text'], // 简单的内容 (会员免费看...)
        ]);
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        $id = $this->option('id');
        if ($id <= 0) {
            Movie::query()
            ->doesntHave('player_sources')
            ->where('douban_id', '>', 0)
            ->where('is_crawler_player_source', false)
            ->chunkById(100, function ($movies) {
                $this->info(sprintf('正在同步 ID 范围为 %s 至 %s 的电影播放源信息', $movies->first()->id, $movies->last()->id));
                foreach($movies as $movie) {
                    $this->info(sprintf('正在同步电影 %s 的播放源信息，豆瓣 ID 为 %s', $movie->name, $movie->douban_id));
                    $data = $this->analysePlaySource($movie->douban_id);
                    $movie->addPlayerSources($data);
                }
            });
            $this->info('同步完成');
        } else {
            if($movie = Movie::where('douban_id', $id)->first()) {
                $result = $this->analysePlaySource($id);
                $movie->addPlayerSources($result);
            } else {
                $this->error(sprintf('电影 %s 数据不存在', $id));
            }
        }
    }
    // 播放源数据分析
    public function analysePlaySource($id)
    {
        $url = config('services.oss.douban.url') . '/' . $id;
        //$ql = QueryList::get($url);

        $rules = [
            'name' => ['a.playBtn', 'data-cn'], // 在哪里看
            'player_url' => ['a.playBtn', 'href'], // 唯一地址
            'content' => ['span.buylink-price', 'text'], // 简单的内容 (会员免费看...)
        ];
        $range = '.gray_ad li';
        $result = $this->ql->get($url)->range($range)->query()->getData()->map(function($item){
            $item['content'] = trim($item['content']);
            $item['player_url'] = urldecode(str_replace('https://www.douban.com/link2/?url=', '', $item['player_url']));
            // 解析出 具体网站
            $site = parse_url($item['player_url']);
            if ( ! isset($site['host'])) {
                return;
            }
            if(isset($site['fragment']) && ! isset($site['query'])) {
                $item['player_url'] = str_replace('#', '?', $item['player_url']);
            } else if ( ! isset($site['query']) && Str::contains($item['player_url'], '&')) {
                $item['player_url'] = Str::replaceFirst('&', '?', $item['player_url']);
            } else {
                $item['player_url'] .= '?rweoryewou54370fsbfds=1';
            }
            $site = parse_url($item['player_url']);
            // 重新组织 url
            $item['url'] = $site['scheme'] . '://' . $site['host'] . $site['path'];
            $item['is_free'] = $item['content'] === '免费观看' ? true : false;
            $item['is_vip_free'] = Str::contains($item['content'], '付费') ? false : true;

            parse_str($site['query'], $player_query);
            $item['type'] = $player_query['subtype'];

            return $item;
        });
        $this->ql->destruct();
        return $result->filter()->all();
    }
}
